package com.ffcs.resource.service;

import com.ffcs.resource.tool.MonitorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ck
 * @date 2024/1/3 15:20
 */
@Service
@Slf4j
public class ResourceService {
    public Thread thread;
    @Value("${resource.cpuThreshold}")
    private double cpu_threshold;

    @Value("${resource.memoryThreshold}")
    private double memory_threshold;

    private List<byte[]> memoryList = new ArrayList<>();

    public double cpuUsage;
    public double memoryUsage;


    public void monitorAndAdjust() throws InterruptedException {
        while (true) {
            cpuUsage = MonitorUtil.getCpuUsage();
            memoryUsage = MonitorUtil.getMemoryUsage();
            log.info("CPU Usage: {}%, Memory Usage: {}%", cpuUsage, memoryUsage);

            adjustCpuUsage(cpu_threshold);

            adjustMemoryUsage(memory_threshold);

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void adjustCpuUsage(double cpu_threshold) {
        if (cpuUsage < cpu_threshold){
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    log.info("未达到cpu阈值，调整资源");
                    while (true) {
                        if (Thread.interrupted()){
                            //如果线程状态为true 结束该线程
                            break;
                        }
                    }
                }
            });
            thread.start();
        }
        else {
            if (thread!=null){
                log.info("中断线程:{},降低cpu使用率",thread.getName());
                //设置该线程状态为true
                thread.interrupt();
            }
        }
    }

    private void adjustMemoryUsage(double memory_threshold) {
        if (memoryUsage < memory_threshold) {
            log.info("未达到memory阈值，调整资源");
            //100M
            byte[] b = new byte[1024 * 100000];
            memoryList.add(b);
        } else {
            if (!memoryList.isEmpty()) {
                memoryList.remove(0);
                log.info("缩减内存list.size:{}", memoryList.size());
                System.gc();
            }
        }
    }
}
